import { Request, Response } from "express";
import { pool } from "../db";
import { ResultSetHeader, RowDataPacket } from "mysql2";

export class ModelController {
  // 获取用户的所有模型
  async getUserModels(req: Request, res: Response) {
    try {
      const userId = req.user?.id; // 从 JWT 中获取
      const [rows] = await pool.execute<RowDataPacket[]>(
        "SELECT * FROM ai_models WHERE user_id = ? AND status = 1 ORDER BY is_default DESC",
        [userId]
      );
      res.json({ code: 0, data: rows });
    } catch (error) {
      res.status(500).json({ code: 500, message: "获取模型列表失败" });
    }
  }

  // 添加新模型
  async createModel(req: Request, res: Response) {
    try {
      const userId = req.user?.id;
      const { name, model, apiKey, baseUrl, isDefault } = req.body;
      console.log(userId, name, model, apiKey, baseUrl, isDefault);

      // 如果设置为默认,先将其他模型设为非默认
      if (isDefault) {
        await pool.execute(
          "UPDATE ai_models SET is_default = 0 WHERE user_id = ?",
          [userId]
        );
      }

      const [result] = await pool.execute<ResultSetHeader>(
        "INSERT INTO ai_models (user_id, name, model, api_key, base_url, is_default) VALUES (?, ?, ?, ?, ?, ?)",
        [userId, name, model, apiKey, baseUrl, isDefault]
      );

      res.json({
        code: 0,
        data: { id: result.insertId },
      });
    } catch (error) {
      res.status(500).json({ code: 500, message: "创建模型失败", error });
    }
  }

  // 更新模型
  async updateModel(req: Request, res: Response) {
    try {
      const userId = req.user?.id;
      const modelId = req.params.id;
      const { name, model, apiKey, baseUrl, isDefault } = req.body;

      // 如果设置为默认,先将其他模型设为非默认
      if (isDefault) {
        await pool.execute(
          "UPDATE ai_models SET is_default = 0 WHERE user_id = ?",
          [userId]
        );
      }

      const [result] = await pool.execute<ResultSetHeader>(
        "UPDATE ai_models SET name = ?, model = ?, api_key = ?, base_url = ?, is_default = ? WHERE id = ? AND user_id = ?",
        [name, model, apiKey, baseUrl, isDefault, modelId, userId]
      );

      if (result.affectedRows === 0) {
        return res
          .status(404)
          .json({ code: 404, message: "模型不存在或无权限修改" });
      }

      res.json({ code: 0, message: "更新成功" });
    } catch (error) {
      res.status(500).json({ code: 500, message: "更新模型失败" });
    }
  }

  // 删除模型
  async deleteModel(req: Request, res: Response) {
    try {
      const userId = req.user?.id;
      const modelId = req.params.id;

      // 软删除,将状态设为0
      const [result] = await pool.execute<ResultSetHeader>(
        "UPDATE ai_models SET status = 0 WHERE id = ? AND user_id = ?",
        [modelId, userId]
      );

      if (result.affectedRows === 0) {
        return res
          .status(404)
          .json({ code: 404, message: "模型不存在或无权限删除" });
      }

      res.json({ code: 0, message: "删除成功" });
    } catch (error) {
      res.status(500).json({ code: 500, message: "删除模型失败" });
    }
  }

  // 设置默认模型
  async setDefaultModel(req: Request, res: Response) {
    try {
      const userId = req.user?.id;
      const modelId = req.params.id;

      await pool.execute(
        "UPDATE ai_models SET is_default = 0 WHERE user_id = ?",
        [userId]
      );

      const [result] = await pool.execute<ResultSetHeader>(
        "UPDATE ai_models SET is_default = 1 WHERE id = ? AND user_id = ?",
        [modelId, userId]
      );

      if (result.affectedRows === 0) {
        return res
          .status(404)
          .json({ code: 404, message: "模型不存在或无权限设置" });
      }

      res.json({ code: 0, message: "设置成功" });
    } catch (error) {
      res.status(500).json({ code: 500, message: "设置默认模型失败" });
    }
  }

  // 获取默认模型
  async getDefaultModel(req: Request, res: Response) {
    try {
      const userId = req.user?.id
      const [rows] = await pool.execute<RowDataPacket[]>(
        'SELECT * FROM ai_models WHERE user_id = ? AND is_default = 1 AND status = 1 LIMIT 1',
        [userId]
      )
      
      if (rows.length === 0) {
        return res.status(404).json({ code: 404, message: '未找到默认模型' })
      }

      res.json({ code: 0, data: rows[0] })
    } catch (error) {
      res.status(500).json({ code: 500, message: '获取默认模型失败' })
    }
  }
}
